import tinyHandle from './handle';
import tinyPlugins from './plugin';
export default class editorConfig {
	constructor(target, options, callback) {
		this.#initializeEditor(target, options, callback);
	}

	#initializeEditor(target, options, callback) {
		let tinyConfig = {
			target,
			skin: 'oxide',
			suffix: '.min',
			menubar: false,
			statusbar: false,
			auto_focus: false,
			language: 'zh_CN',
			plugins: tinyPlugins,
			base_url: '/tinymce',
			paste_data_images: true,
			// 允许 img 标签保留 src（包括外部URL）、alt、width、height 等属性
			valid_elements: '*[*]', // 宽松模式：允许所有标签和属性（不推荐生产环境）
			// 更严格的配置（推荐）：明确允许 img 标签及外部 src
			extended_valid_elements: 'img[src|alt|width|height|class|style|data-*]',
			// 关闭图片上传验证（避免强制转为本地路径）
			images_upload_credentials: false, // 跨域图片不需要携带凭证
			images_reuse_filename: true,
			images_upload_handler: this.handleImageUpload,
			noneditable_regexp: [/\[LOCK\](.*?)\[\/LOCK\]/g],
			content_css: '/tinymce/skins/ui/oxide/content.min.css',
			content_style: 'p { margin: 10px 0; font-size: 14px; color: #303133 }',
		};
		tinymce.init({
			...options,
			...tinyConfig,
			setup: (editor) => {
				editor.on('BeforeSetContent', function(e) {
					e.content = e.content.replace(/\[LOCK\](.*?)\[\/LOCK\]/g, '<span contenteditable="false" class="locked">$1</span>');
				});
				// 提交时把 span 换回 [LOCK] 标签
				editor.on('GetContent', function(e) {
					let regExp = /<span class="locked" contenteditable="false">(.*?)<\/span>/g;
					e.content = e.content.replace(regExp, '[LOCK]$1[/LOCK]');
				});
				tinyHandle.confineDeleteBlock(editor);
				if (!!callback && typeof callback === 'function') {
					callback.call(this, editor);
				}
			}
		});
	}

	handleImageUpload(blobInfo, success, failure) {
		console.log(blobInfo, success, failure);
		success('123123');
	}
}